package com.itmuch.cloud.config;

import io.github.resilience4j.circuitbreaker.CircuitBreakerConfig;
import io.github.resilience4j.timelimiter.TimeLimiterConfig;
import org.springframework.cloud.circuitbreaker.resilience4j.Resilience4JCircuitBreakerFactory;
import org.springframework.cloud.circuitbreaker.resilience4j.Resilience4JConfigBuilder;
import org.springframework.cloud.client.circuitbreaker.Customizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.Duration;

@Configuration
public class Resilience4jConfig {

    /**
     * 配置Resilience4j断路器
     */
    @Bean
    public Customizer<Resilience4JCircuitBreakerFactory> defaultCustomizer() {
        return factory -> factory.configureDefault(id -> {
            // 断路器配置
            CircuitBreakerConfig circuitBreakerConfig = CircuitBreakerConfig.custom()
                    .failureRateThreshold(50) // 失败率阈值，超过这个值断路器会打开
                    .waitDurationInOpenState(Duration.ofSeconds(60)) // 断路器打开状态持续时间
                    .slidingWindowSize(10) // 滑动窗口大小
                    .slidingWindowType(CircuitBreakerConfig.SlidingWindowType.COUNT_BASED) // 基于计数的滑动窗口
                    .permittedNumberOfCallsInHalfOpenState(3) // 半开状态下允许的调用次数
                    .build();

            // 超时配置
            TimeLimiterConfig timeLimiterConfig = TimeLimiterConfig.custom()
                    .timeoutDuration(Duration.ofSeconds(3)) // 超时时间
                    .build();

            return new Resilience4JConfigBuilder(id)
                    .circuitBreakerConfig(circuitBreakerConfig)
                    .timeLimiterConfig(timeLimiterConfig)
                    .build();
        });
    }
}
